<template>
  <view class="uploads">
    <view class="add-form-upload">
      <view class="view-upload-list">
        <view
          class="view-upload-item"
          v-for="(item, index) in filesList"
          :key="index"
          @click="handleView(item)"
        >
          <view class="upload-item-text">
            <img
              src="https://img.alicdn.com/imgextra/i4/1034622205/O1CN01Vr1EEQ1S9wNS8dH1r_!!1034622205.png"
              alt=""
            />
            <text>{{ item.name }}</text>
          </view>
          <view
            class="view-upload-icon"
            @click="remove(index)"
          >
            <i class="iconfont icon-cha"></i>
          </view>
        </view>
      </view>
      <view
        class="view-upload-btn"
        @click="onChange"
      >
        <slot></slot>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, toRefs, watch } from "vue";
import { getTokens, getResourceUpload } from "@/api/index";
import Taro from "@tarojs/taro";
import qiniuUpload from "@/utils/qiniuUploader";
const emits = defineEmits(["files"]);
const props = defineProps(["path", "type"]);
const qiniuToken = ref("");
const uploadsData = ref(undefined);
const type = ref(props.type && props.type != undefined ? props.type : "all");
const filesList = ref([]);
watch(
  () => props.path,
  newVal => {
    console.log(newVal, "pathnewVal");
    filesList.value = newVal;
    if (filesList.value instanceof Array) {
    } else {
      filesList.value = JSON.parse(newVal);
    }
    if (typeof filesList.value == "string") {
      filesList.value = JSON.parse(filesList.value);
    }
  },
);
const handleView = (item: any) => {
  console.log(item, "item");
  Taro.previewImage({
    current: item.url, // 当前显示图片的http链接
    urls: [item.url], // 需要预览的图片http链接列表
  });
};
const onChange = () => {
  chooseDetail();
};
// 移除
const remove = (index: number) => {
  filesList.value.splice(index, 1);
  emits("files", filesList.value);
};
const chooseDetail = async () => {
  Taro.chooseMessageFile({
    type: type.value,
    count: 1,
    success: async function (pre) {
      const tempFilePaths = pre.tempFiles;
      let uploadNum = tempFilePaths.length;
      // 获取文件扩展名
      const fileExt = tempFilePaths[0].name.split(".").pop();
      // 生成有意义的文件名（保留原始文件名）
      const originalName = tempFilePaths[0].name.replace(`.${fileExt}`, "");
      var random = `${Date.now()}_${originalName.split(".")[0]}`;
      const fileName = `user/${Date.now()}_${originalName}.${fileExt}`;
      let params = {
        folder: "fileList",
        fileName: fileName,
        fileType: tempFilePaths[0].type,
        md5: random, //目前作用跟文件名关联的，具体后面再改
      };
      await getTokens(params).then(async (ress: any) => {
        qiniuToken.value = ress.msg;
        new Promise(async (resolve, reject) => {
          for (var i = 0; i < uploadNum; i++) {
            qiniuUpload.upload(
              tempFilePaths[i].path,
              (res: any) => {
                uploadsData.value = res;
                Taro.showToast({
                  title: "上传成功",
                  icon: "success",
                  duration: 2000,
                });
                let resItm = {
                  name: res.fileHash.split("_")[1] + "." + fileName.split(".").pop(),
                  url: res.url,
                };
                filesList.value.push(resItm);
                resolve(filesList.value);
                emits("files", filesList.value);
              },
              (error: string) => {
                reject("error");
              },
              {
                uploadURL: "http://up-z2.qiniup.com", //上传到七牛的那个存储区域，上传区域根据存储空间所在区域决定。
                domain: "qiniu.pudu.live/", //CDN加速域名，此处末尾需加个/  不加的话在res.imageURL返回值中图片访问失败
                uptoken: qiniuToken.value, //服务端接口获取的七牛token值
                region: "ECN",
                key: fileName,
              },
            );
          }
        });
      });
    },
  });
};
</script>

<style lang="less">
@import "./index.less";
</style>
